<template>
    <div>
        <el-row class="risk-order-top">
            <el-col :span="12" class="form-col col-box">
                <!-- 指令表单 -->
                <el-row class="form-content">
                    <!-- 直接还券 -->
                    <el-form label-width="110px" size="small">
                        <el-row class="form-row">
                            <el-col :span="12">
                                <el-form-item label="产品代码:">
                                    <el-select
                                        name="fundCode"
                                        v-model="instruction.fundCode"
                                        size="mini"
                                        filterable
                                        @change="handleFundCodeChange"
                                        clearable
                                    >
                                        <el-option
                                            v-for="i in fundCodeSelectData"
                                            :key="i.fundCode"
                                            :label="i.fundCode + ' ' + i.fundNameSt"
                                            :value="i.fundCode"
                                            :name="'fundCode' + i.fundCode + '~'"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="资产单元编号:" v-show="SHOW_SECURITY">
                                    <el-select v-model="instruction.assetCode" size="mini">
                                        <el-option
                                            v-for="i in computedAssetCodeSelectData"
                                            :key="i.assetCode"
                                            :label="i.assetCode + ' ' + i.assetName"
                                            :value="i.assetCode"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="组合编码:">
                                    <el-select name="组合编码" v-model="instruction.fundAccountCode" size="mini">
                                        <el-option
                                            v-for="i in computedFundAccountCodeSelectData"
                                            :key="i.fundAccountCode"
                                            :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                            :value="i.fundAccountCode"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="证券代码:">
                                    <el-select
                                        name="证券代码"
                                        size="mini"
                                        clearable
                                        filterable
                                        :filter-method="queryMarginTradingPosiotionList"
                                        v-model="instruction.stockCode"
                                        @clear="handleStockCodeClear"
                                        @change="handleStockCodeChange"
                                        @visible-change="handleVisibleChange"
                                    >
                                        <el-option
                                            v-for="i in stockCodeSelectData"
                                            :key="i.stockCode"
                                            :label="i.stockCode + ' ' + i.stockNameSt"
                                            :value="i.stockCode"
                                            :name="'stockCode' + i.stockCode"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="业务类型:" v-show="!SHOW_SECURITY">
                                    <el-select name="业务类型" v-model="instruction.businessType" size="mini" disabled>
                                        <el-option value="x" label="融资融券信用业务"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="委托方向:">
                                    <el-select
                                        name="委托方向"
                                        v-model="instruction.orderDirection"
                                        size="mini"
                                        :disabled="true"
                                        :class="['font-color-' + textColor]"
                                    >
                                        <el-option label="直接还券" value="~" style="color: green"> </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="还券模式:">
                                    <el-select name="还券模式" v-model="repayMode" size="mini" :disabled="true">
                                        <el-option label="即时还券" value="1"> </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="指令数量:">
                                    <RiskInputNumber
                                        :readonly="!instruction.stockCode"
                                        :input="instruction.orderAmount"
                                        :inputAfter="'股'"
                                        :maxlength="15"
                                        :field="'orderAmount'"
                                        :colorStyle="textColor"
                                        :precision="0"
                                        @getInputNumber="getInputNumber(arguments)"
                                    >
                                    </RiskInputNumber>
                                </el-form-item>
                                <el-form-item label="业务类型:" v-show="SHOW_SECURITY">
                                    <el-select name="业务类型" v-model="instruction.businessType" size="mini" disabled>
                                        <el-option value="x" label="融资融券信用业务"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-row>
                <!-- 操作按钮栏 -->
                <el-row class="form-operate">
                    <el-col :span="7">
                        <i style="font-size: 25px" name="entrySetting" class="el-icon-setting iconClass" @click="openEntryGroupDialog"></i>
                    </el-col>
                    <el-col :span="17" style="padding-left: 10px">
                        <el-button name="重置" size="mini" @click="handleClickButtonReset">重置</el-button>
                        <el-button name="试算" type="primary" size="mini" @click="handleTrialCalculate">试算</el-button>
                        <el-button name="下单" type="primary" size="mini" @click="handlePlaceOrder">下单</el-button>
                    </el-col>
                </el-row>
            </el-col>
            <!-- 持仓 -->
            <el-col :span="12" class="col-box">
                <el-tabs type="card" v-model="positionActivePane">
                    <el-tab-pane label="融券标的券持仓" name="1">
                        <RiskTable
                            class="position"
                            :msg="marginPositionListMsg"
                            @getList="queryMarginPositionList"
                            @handleFilter="handleFilterMarginPosition"
                            @handleSort="handleSortMarginPosition(arguments)"
                            @handleBtn="handleMarginPositionSelect"
                        ></RiskTable>
                    </el-tab-pane>
                </el-tabs>
            </el-col>
        </el-row>

        <!-- 条目组设置 -->
        <EntryGroupSetting
            v-if="entryGroupDialog"
            :resourceCode="resourceCode"
            :transDialog="entryGroupDialog"
            @getEntryGroup="getEntryGroup"
            @closeEntryDialog="closeEntryDialog"
        />

        <!--处理下单后的弹窗-->
        <RiskOrderResultAfter
            v-if="orderCancelShow"
            :key="riskOrderResultAfterKey"
            :riskResultThresholdType="trailResultMsg.riskResult"
            :res="riskOrderResultTable"
            @riskResultContinue="riskResultContinue"
            @riskResultCancel="riskResultCancel"
        />
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import EntryGroupSetting from '../components/entry-group-seting.vue';
import RiskTable from '@/common/components/risk-table.vue';
import MarginTradingForm from '../components/margin-trading-form.vue';
import RiskOrderResultAfter from '../components/risk-order-result-after.vue';
import MarginTradingOderClass from '../class/margin-trading-order-class';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import TrailResult from '../components/trail-result.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { queryMarginTradingFunds, queryMarginTradingPosiotions, queryPermissionFunds } from '../api/margin-trading';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { getConfigItem, handleLimitAmount, uniqueFunc } from '@/utils/tools';

@Component({
    name: 'DirectCouponPayMentOrder',
    components: {
        RiskTableLayout,
        RiskTable,
        RiskOrderResultAfter,
        EntryGroupSetting,
        MarginTradingForm,
        StatusTag,
        BranchTag,
        TrailResult,
        RiskInputNumber,
    },
})
// 直接还券下单tab
export default class DirectCouponPayMentOrder extends MarginTradingOderClass {
    @Prop() activePane: string;
    @Prop()
    detail: any;
    iconDom: any = null;
    isFirst: boolean = true;
    instInfo: any = {};

    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    fundCodeSelectData: any[] = [];
    stockCodeSelectData: any[] = []; // 证券代码下拉数据
    selectLoading: boolean = false;
    selectedStockInfo: any = null; // 下拉框选中的证券信息

    instruction = {
        fundCode: '', // 产品代码
        assetCode: '',
        assetName: '',
        fundAccountCode: '', // 组合编码
        fundAccountName: '',
        orderDirection: '~', // 委托方向
        // repayMode: '1', // 还券模式(待确认)
        stockCode: '', // 证券代码
        stockNameSt: '', // 证券名称
        reportCode: '', // 申报代码
        marketCode: '', // 交易市场编码
        businessType: 'x', // 业务类型
        businClass: 'x',
        orderAmount: '', // 指令数量
        fundNameSt: '', // 产品简称
        // fundAccountName: '', // 组合名称
    };
    repayMode: string = '1'; // 还券模式

    // 表单校验字段
    verifyParams: any = {
        fundCode: '产品编码',
        fundAccountCode: '组合编码',
        stockCode: '证券代码',
        orderAmount: '指令数量',
    };

    textColor: string = 'green';

    @Watch('activePane', { immediate: true })
    async onWatchActivePane() {
        if (this.activePane === '5') {
            if (this.isFirst) {
                this.getUserSelectEntryGroupList();
                this.isFirst = false;
            }
        }
    }

    @Watch('instruction.fundCode', { immediate: true, deep: true })
    onWatchFundCode() {
        this.queryMarginPositionList(this.pages);
    }

    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    // 监听 资产单元计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedAssetCodeSelectData', { immediate: true, deep: true })
    watchcomputedAssetCode(newData) {
        if (!this.SHOW_SECURITY) {
            return;
        }
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.assetCode == this.instruction.assetCode);
            obj = d1 || newData[0];
        }
        this.instruction.assetCode = obj.assetCode;
        this.instruction.assetName = obj.assetName;
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.fundAccountCode == this.instruction.fundAccountCode);
            obj = d1 || newData[0];
        }
        this.instruction.assetCode = obj.assetCode;
        this.instruction.assetName = obj.assetName;
        this.instruction.fundAccountCode = obj.fundAccountCode;
        this.instruction.fundAccountName = obj.fundAccountName;
    }

    get computedAssetCodeSelectData(): any {
        return uniqueFunc(this.fundAccountCodeSelectData[this.instruction.fundCode], 'assetCode');
    }

    // 组合编码下拉框计算属性;
    get computedFundAccountCodeSelectData() {
        let data = this.fundAccountCodeSelectData[this.instruction.fundCode];
        let retData = [];
        if (data && this.SHOW_SECURITY) {
            const obj = data.filter(item => item.assetCode == this.instruction.assetCode);
            retData = obj || [];
        } else {
            retData = data;
        }
        return retData;
    }

    // 获取要修改的指令信息
    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail?.instNo && this.detail?.orderDirectionName == '直接还券') {
            // 获取组合编码下拉框数据
            let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
            arr.forEach(item => {
                this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
            });
            let instruction: any = {};
            this.isUpdate = true;
            this.oldOuterOrderCode = this.detail.outerOrderCode;
            this.serialNo = this.detail.serialNo;
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            instruction.businClass = this.detail.businessType;
            instruction.fundAccountCode = this.detail.groupCode;
            this.repayMode = '1';
            this.queryMarginTradingPosiotionList(instruction.stockCode);
            this.getUserSelectEntryGroupList();
            this.handleStockStatus(this.marginPositionListMsg.returnData.data, this.detail?.stockCode);
            this.instInfo = JSON.parse(JSON.stringify(instruction));
        } else {
            this.instInfo = {
                assetCode: '',
                fundAccountCode: '',
            };
        }
        this.instruction = JSON.parse(JSON.stringify(this.instInfo));
        this.instruction.orderDirection = '~';
        this.instruction.businessType = 'x';
        this.instruction.businClass = 'x';
    }

    async mounted() {
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType);
        this.queryfundList();
        this.queryMarginTradingPosiotionList(this.instruction.stockCode);
        // 获取组合编码下拉框数据
        let arr = await DictionConstUtil.FNFundAccount();
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
    }

    // 子组件事件传递--数字输入框组件
    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        if (field == 'orderAmount') {
            setTimeout(() => {
                this.handleOrderAmountChange(value);
            }, 10);
        }
    }

    handleOrderAmountChange(value) {
        if (value.toString() == '0') {
            this.yh_message_warn('指令数量必须大于0！');
            this.instruction.orderAmount = '';
            return;
        }
        let orderAmount = '';
        // 限定指令数量
        let limit = handleLimitAmount(this.textColor, this.selectedStockInfo, value);
        if (!limit) {
            this.instruction.orderAmount = orderAmount;
        }
    }

    handleFundCodeChange(fundCode: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === fundCode) || {};
        this.instruction.fundNameSt = fund.fundNameSt;
    }
    // 查询包含资产单元为融资融券信用资产单元且符合用户权限的基金列表
    queryfundList() {
        Promise.all([queryMarginTradingFunds(), queryPermissionFunds('')])
            .then(res => {
                let fundCodeWithAssetUnit = res[0];
                let fundCodeWithPermission = res[1];
                fundCodeWithAssetUnit.forEach(item => {
                    fundCodeWithPermission.forEach(ele => {
                        if (ele.fundCode === item.fundCode) {
                            this.fundCodeSelectData.push(item);
                        }
                    });
                });
            })
            .catch(err => {
                this.yh_message_error(err);
            });
    }

    handleStockCodeChange(stockCode: string) {
        if (stockCode) {
            this.selectedStockInfo = this.stockCodeSelectData.find(item => item.stockCode === stockCode);
            this.instruction.marketCode = this.selectedStockInfo?.marketNo;
            this.instruction.reportCode = this.selectedStockInfo?.reportCode;
            this.instruction.stockNameSt = this.selectedStockInfo?.stockNameSt;
        } else {
            this.instruction.marketCode = '';
            this.instruction.reportCode = '';
            this.instruction.stockNameSt = '';
        }
        this.handleStockStatus(this.marginPositionListMsg.returnData.data, this.selectedStockInfo?.stockCode);
    }

    // 证券代码清空事件处理
    handleStockCodeClear() {
        this.selectedStockInfo = {};
        this.queryMarginTradingPosiotionList(this.instruction?.reportCode);
        this.handleStockStatus(this.marginPositionListMsg.returnData.data, this.selectedStockInfo?.stockCode);
    }

    handleVisibleChange(state: boolean) {
        if (!state && !this.stockCodeSelectData.length) {
            this.queryMarginTradingPosiotionList('');
        }
    }

    // 查询融券标的券持仓
    queryMarginTradingPosiotionList(val: string | undefined) {
        this.selectLoading = true;
        queryMarginTradingPosiotions({
            sort: '',
            stockNameOrCode: val,
            type: '3',
            paging: this.pages,
            // fundCode: this.instruction.fundCode,
        })
            .then((res: any) => {
                this.stockCodeSelectData = res.list || [];
                this.selectLoading = false;
            })
            .catch(err => {
                this.selectLoading = false;
                this.yh_message_error(err);
            });
    }

    /* ********************* 持仓相关start ******************** */

    // 查询融券标的券持仓
    queryMarginPositionList(pages: any) {
        this.queryPositionList(pages, '3');
    }

    // 融券标的券持仓表格筛选
    handleFilterMarginPosition(filterList: any) {
        this.handleFilterPosition(filterList, '3');
    }

    // 融券标的券持仓表格排序
    handleSortMarginPosition(sort: any) {
        this.handleSortPosition(sort, '3');
    }

    // 选中融券标的券持仓事件
    handleMarginPositionSelect(obj: any) {
        this.selectedStockInfo = obj.row;
        this.instruction.stockCode = obj.row.stockCode;
        this.instruction.reportCode = obj.row.reportCode;
        this.instruction.marketCode = obj.row.marketNo;
        this.queryMarginTradingPosiotionList(this.instruction.reportCode);
        this.handleStockStatus(this.marginPositionListMsg.returnData.data, this.selectedStockInfo?.stockCode);
    }

    /* ********************* 持仓相关end ******************** */

    /* ******************************* 试算、下单start *************************** */

    // 重置表单
    handleClickButtonReset() {
        this.instruction.fundCode = '';
        this.instruction.fundAccountCode = '';
        this.instruction.fundNameSt = '';
        this.instruction.orderAmount = '';
        this.instruction.stockCode = '';
        this.instruction.reportCode = '';
        // super.handleClickButtonReset();
    }
    // 试算
    handleTrialCalculate() {
        this.handleFormSubmit('1');
    }

    // 下单
    handlePlaceOrder() {
        this.handleFormSubmit('2');
    }

    // 继续下达
    riskResultContinue() {
        super.riskResultContinue();
    }

    // 终止下达
    riskResultCancel() {
        super.riskResultCancel();
    }

    /* ******************************* 试算、下单end *************************** */

    /* ************************************ 条目组设置start ********************************** */
    openEntryGroupDialog() {
        this.openEntryGroupDialogs();
    }

    getEntryGroup(value: any) {
        this.getEntryGroups(value);
    }

    closeEntryDialog() {
        this.closeEntryDialogs();
    }

    /* ************************************ 条目组设置end ********************************** */
}
</script>
<style lang="scss" scoped>
// @import '@/pages/risk-measure/style/measure';
@import '@/pages/risk-time/styles/risk-order';
@import '@/pages/risk-time/styles/order-form';
</style>
<style lang="scss">
.messageStyle {
    background-color: #ecf9e3;
    border-color: #ecf9e3;
    font-size: 18px;
    .el-icon-success {
        color: #67c23a;
    }
}
</style>
